package com.serena.da.rest.http_helpers;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;

import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * @author mgrybyk
 *         Post Request
 */
public class PostRequest extends HttpPost {

    public PostRequest(String url) {
        super(url);
    }

    public void setEntity(String payloadString, String contentType) throws UnsupportedEncodingException {
        StringEntity payload = new StringEntity(payloadString);
        payload.setContentType(contentType);
        setEntity(payload);
    }

    /**
     * Add json string to payload
     *
     * @param jsonString json string
     * @throws UnsupportedEncodingException
     */
    public void setEntity(String jsonString) throws UnsupportedEncodingException {
        setEntity(jsonString, "application/json");
    }

    /**
     * Add file to POST body
     *
     * @param bytes byte array file content
     */
    public void setEntity(byte[] bytes) {
        ContentBody body = new ByteArrayBody(bytes, "import.json"); //todo avoid hardcoded file name!
        setFileEntityHelper(body);
    }

    /**
     * Not used. May be useful when we need to put file as request-entity.
     *
     * @param file file
     */
    public void setEntity(File file) {
        ContentBody body = new FileBody(file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
        setFileEntityHelper(body);
    }

    private void setFileEntityHelper(ContentBody body) {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("file", body);
        setEntity(builder.build());
    }
}
